<?php

namespace App\Controller\Admin;

use App\Entity\Topic;
use App\Model\TeacherModel;
use App\Model\TopicModel;
use App\Model\VideoModel;
use App\Setting\VideoSetting;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\Video as Entity;

/**
 * @route("/admin/")
 */
class VideoController extends BaseController4Admin
{

    /**
     * @route("Video/add",name="VideoPreAdd")
     */
    public function add()
    {
        if (!$topicId = $this->getParamRequired("topicId")) {die("topic missed");}
        $uid = $this->needToBeAdmin();
        //通用代码
        $this->setSetting(new VideoSetting($this->getDoctrine()));
        $entity = new Entity();
        $entity->setTopicId($topicId);
        $setting = new VideoSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("VideoDoAdd"));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => true,
        );
        return $this->render("Admin/Video/edit.php.twig",$data);
    }

    /**
     * @route("Video/add/do",name="VideoDoAdd")
     *
     *
     */
    public function doAdd(Request $request)
    {
        $uid = $this->needToBeAdmin();
        $entity = new Entity();
        $entity->setAddtime(time())->setUpdatetime(time());
        $setting = new VideoSetting($this->getDoctrine());
        /**@var $entity ENtity*/
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            $em = $this->getDoctrine()->getManager();
            //更新字段
            $TopicModel = new TopicModel($this->getDoctrine());
            $topic = $TopicModel->getById($entity->getTopicId());
            $entity->setGradeId($topic->getGradeId())
                ->setSubjectId($topic->getSubjectId())
                ->setTeacherId($topic->getTeacherId());

            $em->persist($entity);
            $em->flush();
            $urlData = ["id"=>$entity->getTopicId()];//传参
            return $this->js_out("保存成功",$this->generateUrl("TopicVideoLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("VideoPreAdd"));
        }
    }

    /**
     * @route("Video/edit/{id}",name="VideoPreEdit")
     */
    public function edit(Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new VideoSetting($this->getDoctrine()));
        $setting = new VideoSetting($this->getDoctrine());
        $from = $this->getFormCreator()->createAddFrom($entity,$setting->formConfig(),$this->generateUrl("VideoDoEdit",["id"=>$entity->getId()]));
        $data = array(
            "title" => $this->entitySetting->entityCnName,
            "show"   => $from->createView(),
            "isAdd"   => false,
        );
        return $this->render("Admin/Video/edit.php.twig",$data);
    }

    /**
     * @route("Video/edit/{id}/do",name="VideoDoEdit")
     *
     *
     */
    public function doEdit(Request $request,Entity $entity)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new VideoSetting($this->getDoctrine()));
        $setting = new VideoSetting($this->getDoctrine());
//        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {

        /**@var $entity ENtity*/
        if ($entity = $this->getFormCreator()->fillEntity($entity,$request,$setting->formConfig())) {
            //更新字段
            $TopicModel = new TopicModel($this->getDoctrine());
            $topic = $TopicModel->getById($entity->getTopicId());
            $entity->setGradeId($topic->getGradeId())
                ->setSubjectId($topic->getSubjectId())
                ->setTeacherId($topic->getTeacherId());

            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $urlData = ["id"=>$entity->getTopicId()];//传参
            return $this->js_out("保存成功",$this->generateUrl("TopicVideoLists",$urlData));
        } else {
            return $this->js_out("系统错误，请联系管理员",$this->generateUrl("VideoPreEdit",array("id"=>$entity->getId())));
        }
    }

    /**
     * @route("Video",name="VideoLists")
     */
    public function lists()
    {
        $uid = $this->needToBeAdmin();
        //私有部分
        $tools = array();
        //通用部分
        $this->setSetting(new VideoSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $model = new VideoModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }

        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
        $params["groupBy"][$table]=array("id");
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);

        //$lists = $this->getLists($page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("VideoTools"),
            "addUrl"=>$this->generateUrl("VideoPreAdd"),
        );
        $entityCnName = $this->entitySetting->entityCnName;
        return $this->render("Admin/Video/list.php.twig", array(
            'title'     => "$entityCnName 列表",
            "tools"   => $tools,
            'urls'      => $urls,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("VideoLists"),$total,$per_page),
        ));
    }

    /**
     * @route("Video/tools/{id}",name="VideoTools")
     */
    public function tools(Request $request,Topic $topic)
    {
        $uid = $this->needToBeAdmin();
        $this->setSetting(new VideoSetting($this->getDoctrine()));
//        return $this->comTools($request);
        if($__EVENTTARGET = $this->getParamRequired("__EVENTTARGET")){
            unset($_GET['__EVENTTARGET']);
        }else{
            return $this->js_out("参数丢失",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
        }
        if($__EVENTARGUMENT = $this->getParamRequired("__EVENTARGUMENT")){
            unset($_GET['__EVENTARGUMENT']);
        }
        $em = $this->getDoctrine()->getManager();
        //如果是删除操作执行删除操作
        if ($__EVENTTARGET == "multiDelete") {
            if($ids = $this->getParamRequired("ids")){
                unset($_GET['ids']);
            }else{
                return $this->js_out("参数丢失",$this->redirectToRoute($this->entitySetting->entityName."Lists"));
            }
            if (is_array($ids) && !empty($ids)) {
                foreach ($ids as $id) {
                    $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$id);
                    $em->remove($entity);
                }
                $em->flush();
            }
        }
        //如果是修改操作执行修改操作
        if ($__EVENTTARGET == "setAttr") {
            parse_str($__EVENTARGUMENT,$data);
            if (is_array($data) && isset($data["id"])) {
                $entity  = $em->find($this->entitySetting->bundleName.":".$this->entitySetting->entityName,$data["id"]);
                unset($data["id"]);
                foreach ($data as $key => $val) {
                    if ( !in_array( $key , $this->entitySetting->editKeys ) ) { continue; }
                    $func = "set$key";
                    $entity->$func($val);
                }
                $em->persist($entity);
                $em->flush();
            }
        }
        //否则将参数传递至list
        $cond["cond"] = $request->get("cond");
        $queryStr = http_build_query($cond);
        if ($txtKeywords = $request->get("txtKeywords")) {
            $queryStr .= "&txtKeywords=".$txtKeywords;
        }
        return $this->redirect($this->generateUrl("TopicVideoLists",["id"=>$topic->getId()])."?".$queryStr);
    }

    /**
     * @route("Video/inTopic/{id}",name="TopicVideoLists")
     */
    public function TopicVideoLists(Topic $topic)
    {

        $uid = $this->needToBeAdmin();

        $TeacherModel = new TeacherModel($this->getDoctrine());
        $teacher = $TeacherModel->getById($topic->getTeacherId());

        //私有部分
        $tools = array();
        //通用部分
        $this->setSetting(new VideoSetting($this->getDoctrine()));
        /*分页配置*/
        if (!$page   = $this->getParamRequired("page")) { $page = 1;}
        $per_page   = $this->entitySetting->perPage;
        $model = new VideoModel($this->getDoctrine());
        $params = array();
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ($val === "") {
                    continue;
                }
                $params["conditions"][$this->entitySetting->table][$key]["eq"]=$val;
            }
        }
        $params["conditions"][$this->entitySetting->table]["topicId"]["eq"]=$topic->getId();
        if ($txtKeywords) {
            $params["textKey"] = "%$txtKeywords%";
        }
        $table = str_replace("_","",$this->entitySetting->table);
        $params["groupBy"][$table]=array("id");
        $lists = $model->getAdminLists($params,$page * $per_page - $per_page,$per_page);

        //$lists = $this->getLists($page,$per_page);
        $total = $lists["total"];
        $this->smartFormat($lists["data"]);

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl("VideoTools",["id"=>$topic->getId()]),
            "addUrl"=>$this->generateUrl("VideoPreAdd",["topicId"=>$topic->getId()]),
        );
        $entityCnName = $this->entitySetting->entityCnName;
        return $this->render("Admin/Video/list.php.twig", array(
            'title'     => "$entityCnName 列表",
            "topic"     => $topic,
            "teacher"   => $teacher,
            "tools"     => $tools,
            'urls'      => $urls,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl("TopicVideoLists",["id"=>$topic->getId()]),$total,$per_page),
        ));
    }
}
